package com.app.babygo;

import java.util.ArrayList;
import java.util.HashMap;

import com.app.babygo.dbservice.AchievementAdapter;
import com.app.babygo.exceptions.InternalDBException;
import com.app.babygo.obj.AchievementTask;
import com.app.babygo.obj.Child;
import com.app.babygo.obj.ChildAchievement;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class TaskList extends Activity {
	protected static final String TAG = "TaskListPage";
	protected static final String SELECTED_TASK_KEY = "SelectedTask";
	protected static final String IS_COMPLETED_KEY = "IsTaskCompleted";
	protected static final String TASK_COMPLETE_DETAIL_KEY = "TaskCompleteDetail";
	protected static boolean needRefresh = false;
	protected Child SelectedChild; 
	protected ArrayList<AchievementTask> TaskList;
	protected HashMap<String, ChildAchievement> CompleteTasks = new HashMap<String, ChildAchievement>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_list);
		loadTaskList();
		createUI();
	}

	private void createUI() {
		ListView listView = (ListView)this.findViewById(R.id.android_task_list_view);
		listView.setAdapter(new TaskItemAdapter(this));
		Button createTaskBtn = (Button)this.findViewById(R.id.create_new_task_btn);
		ImageView headerImg = (ImageView)this.findViewById(R.id.header_img);
		Bitmap bitmap = BitmapFactory.decodeFile(SelectedChild.getChildPicPath());
		headerImg.setImageBitmap(bitmap);
		createTaskBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), TaskCreation.class);
				startActivity(intent);
			}
		});
	}

	private void loadTaskList() {
		Intent intent = this.getIntent();
		SelectedChild = (Child)intent.getSerializableExtra(ChildChoose.SELECTED_CHILD_KEY);
		AchievementAdapter dbTask = new AchievementAdapter(this);
		dbTask.open();
		try {
			TaskList = dbTask.getAchievementTaskList(); // should we cache this? try test it.
			CompleteTasks = dbTask.getChildAchievementMap(SelectedChild.getCid());
		} catch (InternalDBException e) {
			Log.e(TAG, "Error getting task list: " + e.getMessage());
		}
		dbTask.close();
		
	}
	
	private void reloadTaskList() {
		AchievementAdapter dbTask = new AchievementAdapter(this);
		dbTask.open();
		try {
			TaskList = dbTask.getAchievementTaskList(); // should we cache this? try test it.
			CompleteTasks = dbTask.getChildAchievementMap(SelectedChild.getCid()); 
		} catch (InternalDBException e) {
			Log.e(TAG, "Error getting task list: " + e.getMessage());
		}
		dbTask.close();
		ListView listView = (ListView)this.findViewById(R.id.android_task_list_view);
		listView.setAdapter(new TaskItemAdapter(this));
	}
	
	public static void expireCurrentView(){
		needRefresh = true;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (needRefresh) {
			reloadTaskList();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.child_info, menu); // TODO: change menus options
		return true;
	}
	
	public final class ViewHolder{
        //public ImageView img;
        public TextView taskTitle;
        public TextView taskStatus;
        public View itemView;
        public ChildAchievement achievement; 
	}
	
	class TaskItemAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		
		public TaskItemAdapter(Context context) {
			super();
			inflater = LayoutInflater.from(context);
		
		}
		
		public Object getItem(int position) {
			return TaskList.get(position);
		}
		
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getCount() {
			return TaskList.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			final AchievementTask taskObject = TaskList.get(position);
            if (convertView == null) {
                holder=new ViewHolder(); 
                convertView = inflater.inflate(R.layout.task_item_layout, null);
                holder.taskTitle = (TextView)convertView.findViewById(R.id.task_title);
                holder.taskStatus = (TextView)convertView.findViewById(R.id.task_status);
                convertView.setTag(holder); //cache this item view
                
            }else {
                holder = (ViewHolder)convertView.getTag();
            }
           
            holder.taskTitle.setText(taskObject.getTaskname());
            if (CompleteTasks.containsKey(taskObject.getTaskid()))
            {
            	convertView.setBackgroundResource(R.drawable.box_green);
            	ChildAchievement achievement = CompleteTasks.get(taskObject.getTaskid());
            	String status = String.format("[Completed: %tD]", achievement.getAchievementDate());
            	holder.taskStatus.setText(status);
            }
            else
            {
            	convertView.setBackgroundResource(R.drawable.box_grey);
            	holder.taskStatus.setText("[Incomplete]");
            }
            
            convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(inflater.getContext(), TaskDetail.class);
					intent.putExtra(SELECTED_TASK_KEY, taskObject);
					String taskid = taskObject.getTaskid();
					boolean isCompleted = CompleteTasks.containsKey(taskid);
					intent.putExtra(IS_COMPLETED_KEY, isCompleted);
					if (isCompleted) {
						intent.putExtra(TASK_COMPLETE_DETAIL_KEY, CompleteTasks.get(taskid));
					}
					startActivity(intent);
					overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
				}
			});
            
			return convertView;
		}
	}

}
